export function didMount() {
    console.log("「页面 JS」：当前页面地址 " + location.href);

    const echartsScriptTag = document.createElement('script');
    echartsScriptTag.src = 'https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js';
    document.head.appendChild(echartsScriptTag);

    const self = this;

    const ddcatSources = [
        { id: "ds_mod:b49a09d0-f3ce-4706-89b3-0f9c0df5e40e", name: "专项检查计划-计划统计分析" },
        { id: "ds_mod:f2912034-e78a-49eb-b828-a06f615126a8", name: "专项检查计划- 时间分布" }
    ];

    // 加载计划/备案数据
    fetchDdcatData(ddcatSources[0].id).then(res => {
        if (res && res.length) {
            loadTwoRingPieChart(self, res);
        } else {
            // 数据为空，使用模拟数据
            const mockData = getRandomNum();
            loadTwoRingPieChart(self, mockData);
        }
    });

    // 加载时间分布柱状图
    fetchDdcatData(ddcatSources[1].id).then(res => {
        if (res && res.length) {
            loadTimeBarChart(self, res);
        } else {
            // 数据为空，使用模拟数据
            const mockInspectionData = generateMockInspectionPlanData();
            loadTimeBarChart(self, mockInspectionData);
        }
    });
}


/**
 * 加载时间分布柱状图
 */
function loadTimeBarChart(self, data) {
    const chartContainer = self.$$("text_6i3m3t").$el;
    const myChart = echarts.init(chartContainer);

    // 把数据按照月份归类
    const monthMap = {};
    debugger
    data.forEach(item => {
        let timeStr = item.planTime;
        const month = timeStr.slice(0, 7);
        const planCount = item.planCount || 0;
        monthMap[month] = (monthMap[month] || 0) + planCount;
    });

    // 排序一下月份
    const months = Object.keys(monthMap).sort();
    const counts = months.map(m => monthMap[m]);

    const option = {
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: months,
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                rotate: 0,
                color: 'rgba(0, 0, 0, 0.5)'
            }
        },
        yAxis: {
            type: 'value'
        },
        grid: {
            left: '5%',
            right: '2%',
            bottom: '20%',
            top: '15%'
        },
        series: [{
            type: 'bar',
            data: counts,
            itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    { offset: 0, color: '#3399FF' },
                    { offset: 1, color: '#66CCFF' }
                ])
            },
            barWidth: '15%'
        }]
    };

    myChart.setOption(option);
}


/**
 * 加载两个环形图（计划总数 + 备案总数）
 */
function loadTwoRingPieChart(self, data) {

    const chartContainer = self.$$("text_1m09ic").$el;
    const myChart = echarts.init(chartContainer);

    // 模拟分成两组数据（按你的需求调整）
    const planData = data.filter(item => item.planType === '计划'); // 假设字段
    const recordData = data.filter(item => item.planType === '备案'); // 假设字段

    // 计算总数
    const planTotal = planData.reduce((sum, item) => sum + Number(item.deviceNum), 0);
    const recordTotal = recordData.reduce((sum, item) => sum + Number(item.deviceNum), 0);

    // 转换成环形图需要的数据
    const formatData = (list) => {
        const total = list.reduce((sum, item) => sum + Number(item.deviceNum), 0);
        return list.map(item => ({
            name: item.regionName,
            value: Number(item.deviceNum),
            percentage: total === 0 ? 0 : parseFloat((item.deviceNum / total * 100).toFixed(2))
        }));
    };

    const planRingData = formatData(planData);
    const recordRingData = formatData(recordData);

    // 渐变色配置
    const gradientColors = [
        { start: '#85C0FF', end: '#3388FF' },
        { start: '#FFD152', end: '#FFAA00' },
        { start: '#5CE0B6', end: '#11C79B' }
    ];
    const createGradient = (index) => {
        const gradient = gradientColors[index % gradientColors.length];
        return new echarts.graphic.LinearGradient(0, 0, 1, 1, [
            { offset: 0, color: gradient.start },
            { offset: 1, color: gradient.end }
        ]);
    };

    const option = {
        legend: {
            orient: 'vertical',
            left: 'center',
            top: 'center',
            data: ['省（市）级', '市（区）级', '县级'],
            itemWidth: 15,
            itemHeight: 10,
            itemGap: 15,
        },
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        series: [
            {
                type: 'pie',
                name: '计划总数',
                radius: ['65%', '80%'],
                center: ['30%', '50%'],
                label: { show: false },
                emphasis: { label: { show: false } },
                data: planRingData.map((item, index) => ({
                    name: item.name,
                    value: item.value,
                    itemStyle: { color: createGradient(index) }
                }))
            },
            {
                type: 'pie',
                name: '备案总数',
                radius: ['65%', '80%'],
                center: ['70%', '50%'],
                label: { show: false },
                emphasis: { label: { show: false } },
                data: recordRingData.map((item, index) => ({
                    name: item.name,
                    value: item.value,
                    itemStyle: { color: createGradient(index) }
                }))
            }
        ],
        graphic: [
            {
                type: 'text',
                left: '25.52%',
                top: '33%',
                style: {
                    text: `{total|${planTotal}}\n{label|计划总数}`,
                    textAlign: 'center',
                    rich: {
                        total: {
                            fontSize: 24,
                            fontWeight: 500,
                            lineHeight: 34,
                            color: '#223355'
                        },
                        label: {
                            fontSize: 14,
                            fontWeight: 400,
                            color: '#223355;'
                        }
                    }
                }
            },
            {
                type: 'text',
                left: '65.7%',
                top: '33%',
                style: {
                    text: `{total|${recordTotal}}\n{label|备案总数}`,
                    textAlign: 'center',
                    rich: {
                        total: {
                            fontSize: 24,
                            fontWeight: 500,
                            lineHeight: 34,
                            color: '#223355'
                        },
                        label: {
                            fontSize: 14,
                            fontWeight: 400,
                            color: '#223355'
                        }
                    }
                }
            }
        ]
    };

    myChart.setOption(option);
}

/**
 * 从 ddcat 数据源拉取所有数据
 * @returns Promise<数组> - 返回结果数组
 */
function fetchDdcatData(sourceId) {
    const jsonParams = { pageSize: 99999 };
    return api.DATA_SOURCE_EXECUTE(
        sourceId,
        "ddcat",
        [],
        [],
        JSON.stringify(jsonParams)
    ).then(res => {

        if (res && !res.hasError && res.result != null) {
            return res.result;
        } else {
            console.warn("查询失败或数据为空，生成模拟数据");
            // 这里生成模拟数据
            return [];
        }
    });
}

/**
 * 获取当前月往前推六个月的模拟数据
 * 数据包含时间（planTime）和检查计划个数（planCount）
 */
function generateMockInspectionPlanData() {
    const currentDate = new Date();
    const months = []; // 用于存储时间数据
    const mockData = []; // 用于存储最终的模拟数据

    // 获取当前月及过去六个月的月份
    for (let i = 0; i < 6; i++) {
        const month = new Date(currentDate.setMonth(currentDate.getMonth() - 1));
        const monthStr = month.toISOString().slice(0, 7); // 格式化为 YYYY-MM
        months.push(monthStr);
    }

    // 为每个月生成模拟检查计划个数数据
    months.forEach(month => {
        mockData.push({
            planTime: month + '-01', // 假设每天都是这个月份的第一天
            planCount: Math.round(Math.random() * 100 + 50) // 随机生成检查计划个数（50到150之间）
        });
    });

    return mockData;
}


/**
 * 获取（计划总数 + 备案总数）模拟数据
 */
function getRandomNum(){
    const baseData = [
        { regionName: "省（市）级", baseNum: 120, planType: "计划" },
        { regionName: "市（区）级", baseNum: 80, planType: "计划" },
        { regionName: "县级", baseNum: 60, planType: "计划" },
        { regionName: "省（市）级", baseNum: 100, planType: "备案" },
        { regionName: "市（区）级", baseNum: 70, planType: "备案" },
        { regionName: "县级", baseNum: 50, planType: "备案" }
    ];

    // 给每个基础值加一个小随机偏差，比如 ±10%
    const getRandomDeviceNum  = (base) => {
        const fluctuation = base * 0.1; // 10%的浮动
        const randomOffset = (Math.random() * fluctuation * 2) - fluctuation; // [-10%, +10%]
        return Math.round(base + randomOffset);
    };

    return baseData.map(item => ({
        regionName: item.regionName,
        deviceNum: getRandomDeviceNum (item.baseNum),
        planType: item.planType
    }));

}
